import os
from win32com import client

def doc2pdf(doc_name, pdf_name):
    try:
        word = client.DispatchEx("Word.Application")
        if os.path.exists(pdf_name):
            os.remove(pdf_name)
        worddoc = word.Documents.Open(doc_name, ReadOnly=1)
        worddoc.SaveAs(pdf_name, FileFormat=17)
        worddoc.Close()
        return pdf_name
    except:
        return 1

def convert_files(current_dir):
    files = os.scandir(current_dir)
    files = [i for i in files if '.doc' in os.path.basename(i)]
    for i in files:
        input = os.path.abspath(i)
        output = f'{current_dir}\\{os.path.basename(i).split(".")[0]}.pdf'
        count = 1
        while os.path.exists(output):
            output = f'{current_dir}\\{os.path.basename(i).split(".")[0]}_{count}.pdf'
            count += 1
        rc = doc2pdf(input, output)
        if rc:
            print(os.path.basename(i),'转换成功')
        else:
            print(os.path.basename(i),'转换失败')

def main():
    print('开始转换，请稍等。。。')
    path = os.getcwd()
    convert_files(path)
    subdirectories = [x[0] for x in os.walk(path)]
    subdirectories.remove(path)  
    for subdir in subdirectories:
        convert_files(subdir)

if __name__ == '__main__':
    main()
